/**
 *  Copyright (C) 2008 Richard Hall
 *
 *  This program is free software; you can redistribute it and/or modify it under the terms of the 
 *  GNU General Public License as published by the Free Software Foundation; either version 3 of the 
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along with this program; if not, 
 *  see <http://www.gnu.org/licenses>.
 *
 *  Additional permission under GNU GPL version 3 section 7
 *
 *  If you modify this Program, or any covered work, by linking or combining it with [name of library] 
 *  (or a modified version of that library), containing parts covered by the terms of 
 *  [name of library's license], the licensors of this Program grant you additional permission to 
 *  convey the resulting work. {Corresponding Source for a non-source form of such a combination shall 
 *  include the source code for the parts of [name of library] used as well as that of the 
 *  covered work.}
 *
 * 
 */

package com.gpsmedia.uploadutils;

import com.blipnetworks.util.Authenticator;
import com.blipnetworks.util.Parameters;
import com.blipnetworks.util.Uploader;
import com.blipnetworks.util.RandomGUID;
import java.io.*;
import java.net.*;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpException;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;

/**
 * This class is a wrapper class to make use of the functions that are required
 * from the Blip.tv api. It enables the upload of mp3 files to Blip.tv and
 * retrieves a URL for use later.
 * <p>
 * <p>
 * http://blip.tv/about/api/
 * <p>
 * 
 * @author Richard Hall
 */
public class BlipTvTools {

    private Cookie authCookie;
    private String guid;
    private String fileURL;

    /**
	 * Constructor for this class.
	 * 
	 * @param username
	 *            The user name
	 * @param password
	 *            The password
	 * @throws Exception
	 */
    public BlipTvTools(String username, String password) throws Exception {

        authCookie = Authenticator.authenticate(username, password);

    }

    /**
	 * Uploads the file with a title and a description
	 * 
	 * @param file
	 *            The file
	 * @param title
	 *            The title
	 * @param description
	 *            The description
	 */
    public void doUpload(File file, String title, String description) {
        try {
            fileURL = "";
            // Create a properties object to hold the form data/metadata
            Properties props = new Properties();

            props.put(Parameters.TITLE_PARAM_KEY, title);
            // Add the description
            props.put(Parameters.DESC_PARAM_KEY, description);
            // Create an uploader instance with the authCookie object
            Uploader uploader = new Uploader(authCookie);
            // Create a new random GUID
            guid = new RandomGUID().toString();

            uploader.setGuid(guid);

            uploader.uploadFile(file, props);
            fileURL = uploader.getPostURL();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(BlipTvTools.class.getName()).log(Level.SEVERE, null, ex);
        } catch (HttpException ex) {
            Logger.getLogger(BlipTvTools.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(BlipTvTools.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(BlipTvTools.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            Logger.getLogger(BlipTvTools.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns the URL for the uploaded file
     * There is no functionality supplied in the API to point to just the 
     * mp3 file. Therefore I am using web page scraping to retrieve the path.
     *      
     * @return The URL to the file
     */
    
    public String getFileURL() {

        InputStream is = null;

        String returnString = "";

        try {
            URL address = new URL(fileURL);
            is = address.openStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);

            String line = br.readLine();
            while (line != null) {
                if (line.contains("player.setPrimaryMediaUrl".subSequence(0, 25)) == true) {
                    returnString = line.substring(line.indexOf("http:"), line.indexOf("?"));
                    line = null;
                } else {
                    line = br.readLine();
                }
            }




        } catch (IOException ex) {
            Logger.getLogger(BlipTvTools.class.getName()).log(Level.SEVERE, null, ex);
        } finally {

            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(BlipTvTools.class.getName()).log(Level.SEVERE, null, ex);
            }

            return returnString;
        }
    }
}
